package mcom.xmks.bluetooth.mesh.ota;

import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * 共享文件解析程序
 */
public class ShareFileResolver {
    /**
     * Uri到文件
     * @param context 上下文
     * @param uri Uri路径
     * @param newName 保存到
     * @throws Exception
     */
    public static void uriToFile(Context context, Uri uri,String newName)throws Exception {
        File target = UpdateFileResolver.getTargetImageFile(context, newName);
        if(!target.exists()){
            if(!target.createNewFile()){
                throw new Exception("create file fail");
            }
        }
        ContentResolver contentResolver = context.getContentResolver();
        InputStream is = contentResolver.openInputStream(uri);
        OutputStream os = new FileOutputStream(target);
        write(is,os);
    }


    //将输入流的数据拷贝到输出流
    public static void write(InputStream is, OutputStream os) throws IOException {
        byte[] buffer = new byte[1024 * 1024];
        while (true) {
            int len = is.read(buffer);
            if (len < 0) break;
            os.write(buffer, 0, len);
        }
        os.flush();
        is.close();
        os.close();
    }
}
